package com.eastcode.base.action;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.eastcode.base.util.DateUtil;
import com.eastcode.base.util.ObjectConvertUtil;
import com.eastcode.base.util.ObjectUtil;
import com.eastcode.base.util.StringUtil;

/**
 * 该类是所有action类的基类，request请求， 进行action执行前的准备工作。
 * 
 * @author 王一进
 * 
 */
public abstract class BaseAction extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected HttpSession session;
	protected ServletContext servletContext;

	private String message = "";

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		this.request = request;
		this.response = response;
		this.session = request.getSession();
		this.servletContext = request.getSession().getServletContext();

		// 执行
		execute();
	}

	/**
	 * 默认执行方法
	 * 
	 */
	protected abstract void execute();

	/**
	 * 方法调用
	 * 
	 * @param t
	 */
	protected <T> void prepare(T t) {
		request.setAttribute("base", parseServer(request));

		// 解析请求参数
		String cmd = request.getParameter("cmd");
		if (!StringUtil.isEmpty(cmd)) {
			try {
				Method method = t.getClass().getMethod(cmd);
				method.invoke(t);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 从request中分离出域名及端口
	 * 
	 * @param request
	 * @return
	 */
	public String parseServer(HttpServletRequest request) {
		String serverName = "http://" + request.getServerName();
		int serverPort = request.getServerPort();
		if (serverPort != 80) {
			serverName = serverName + ":" + String.valueOf(serverPort);
		}

		// 合并生成
		serverName += request.getContextPath();

		return serverName;
	}

	public void forward(String path) {
		if (request != null && request.getSession(false) != null) {
			try {
				request.getRequestDispatcher(path).forward(request, response);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	/**
	 * 设置结果
	 * 
	 * @param object
	 */
	public void setResult(Object object) {
		Map<String, Object> result = ObjectConvertUtil.objectToMapAll(object);
		Iterator<String> iterator = result.keySet().iterator();

		while (iterator.hasNext()) {
			String key = iterator.next();
			Object obj = result.get(key);
			if (obj instanceof Date) {
				obj = DateUtil.getDateTimeStr((Date) obj);
			}
			request.setAttribute(key, String.valueOf(obj));
		}
	}

	/***
	 * 解析request中的参数，组装对象
	 * 
	 * @param t
	 * @return
	 */
	public <T> T parseRequest(Class<T> cls, String prefix) {

		try {
			T t = cls.newInstance();
			Method[] methods = t.getClass().getMethods();

			for (Method method : methods) {
				String key = "";

				String methodName = method.getName();
				if (methodName.startsWith("set")) {
					key = methodName.substring(3);
				} else {
					continue;
				}

				// 计算key值
				key = Character.toLowerCase(key.charAt(0)) + key.substring(1);
				String param = request.getParameter(prefix + key);

				if (param != null && param.length() > 0) {
					Class<?>[] paramClass = method.getParameterTypes();

					// 类型判断
					method.invoke(t, ObjectUtil.convert(paramClass[0], param));
				}
			}
			return t;
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return null;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

}
